package cn.madis.ymcc.security;

import cn.madis.ymcc.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;




/**
 *  web安全配置类(认证授权配置)
 */
@Configuration

//开启web安全配置
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled= true)//开启方法授权
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private IPermissionService permissionService;

    //配置认证管理器，授权模式为“poassword”时会用到
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    //提供用户信息 + 权限，这里没有从数据库查询用户信息，在内存中模拟
    // 浏览器输入账号密码，点击登录按钮，Security兰街到账号密码，然后和内存中的InMemoryUserDetailsManager提供的User作比较
    //比较密码的时候会使用提供的PasswordEncoder实体，去对前端传递过来的密码做处理之后和内存中的User的password作比较
    // 如果全部比对成功，跳转到登录成功页面
    // 如果不对不成功，报错？？？
    /*@Bean
    public UserDetailsService userDetailsService(){
        //内存中写死一个login
        InMemoryUserDetailsManager inMemoryUserDetailsManager =
        new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(User.withUsername("zs").password("123").authorities("admin").build());
        return inMemoryUserDetailsManager;
    }*/


    //密码编码器：不加密
    /*
      登录的时候，Security会根据调用我们自己写的LoginUserDetailsService中的方法loadUserByUsername 拿到数据库中login和权限信息
      使用PasswordEncoder 去比对密码


     */

    /*public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        *//*String pwd1 = encoder.encode("123");
        String pwd2 = encoder.encode("123");*//*
     *//*System.out.println(pwd1);
        System.out.println(pwd2);*//*
        boolean ma1 = encoder.matches("123", "$2a$10$tYQsAI/HsDs2GgkTJ7Ftou93eGtEDrHmShckQWtK4pmXfKmWMuN3y");
        boolean ma2 = encoder.matches("123", "$2a$10$Qcw0dAkhAPp8z1Gtt5Ga6OYUfQ3i4s4KrSEYMHdRoF5PqLQmU5kBi");
        System.out.println(ma1);
        System.out.println(ma2);


    }*/

    @Bean
    public PasswordEncoder passwordEncoder(){
        //明文比较密码
        return new BCryptPasswordEncoder();
    }

    //授权规则配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // web授权
       /* List<Permission> permissions = permissionService.selectList(null);
        permissions.stream().forEach(p->{
            try {
                http.authorizeRequests().antMatchers(p.getResource()).hasAuthority(p.getSn());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });*/
        http.authorizeRequests()                                //授权配置
                .antMatchers("/login/common").permitAll()  //登录路径放行
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().formLogin()                              //允许表单登录
                          // 设置登陆成功页
                .and().logout().permitAll()                    //登出路径放行 /logout
                .and().csrf().disable();                        //关闭跨域伪造检查
    }
}
